//
//  YRRefreshControl.swift
//  YR 微博
//
//  Created by cyr on 15/10/20.
//  Copyright © 2015年 cyr. All rights reserved.
//

import UIKit

private let kRefreshPullOffset:CGFloat = -60

/// 下拉刷新控件,集成在 tableView controller
class YRRefreshControl: UIRefreshControl {

    // 重写系统方法
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopLoading()
    }
    
    
    // MARK: - kvo
   
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if frame.origin.y > 0 {
            return
        }
        
        if refreshing {
            refreshView.startLoading()
        }
        
        if frame.origin.y < kRefreshPullOffset && !refreshView.rotateFlag{
            print("翻过来")
            refreshView.rotateFlag = true
        } else  if frame.origin.y > kRefreshPullOffset && refreshView.rotateFlag {
            print("转过去")
            refreshView.rotateFlag = false
        }
    }
    
    
    // MARK: - 构造函数
    override init() {
        super.init()
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    deinit {
        
        self.removeObserver(self, forKeyPath: "frame")
    }
    
    private func setupUI() {
        
        // KVO 监听frame 变化
        self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        
        tintColor = UIColor.clearColor()
        
        addSubview(refreshView)
        
        // 自动布局
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)
    }
    
    // MARK: - 懒加载控件
    
    private lazy var refreshView: YRRefreshView = YRRefreshView.refreshView()

}


/// 下拉刷新视图- 负责显示和动画
class YRRefreshView: UIView {
    /// 旋转标记
    private var rotateFlag = false {
        didSet {
            rotateTipIcon()
        }
    }
    
    @IBOutlet weak var tipIcon: UIImageView!
    @IBOutlet weak var loadingIcon: UIImageView!
    @IBOutlet weak var tipView: UIView!
    
    
    class func refreshView() -> YRRefreshView {
       return NSBundle.mainBundle().loadNibNamed("YRRefreshView", owner: nil, options: nil).last as! YRRefreshView
    }
    
    /**
    提示图标的旋转
    */
    private func rotateTipIcon() {
        let angle = self.rotateFlag ? CGFloat(M_PI - 0.01) : CGFloat(M_PI + 0.01)
        UIView.animateWithDuration(0.25) { () -> Void in
            
            self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, angle)
        }
    }
    
    /**
    *  开始加重动画
    */
    private func startLoading() {
        
        if loadingIcon.layer.animationForKey("loadingAinm") != nil {
            return
        }
        
        tipView.hidden = true
        
        // 定义动画
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 1.0
        
        loadingIcon.layer.addAnimation(anim, forKey: "loadingAnim")
    }
    
    /**
    *  停止加载动画
    */
    private func stopLoading() {
        tipView.hidden = false
        loadingIcon.layer.removeAllAnimations()
        
    }
}